/**
 * Created by wqz806687102 on 2016/1/11.
 */
'use strict';

angular.module('Query').controller('PostsRecordController', ['$scope', '$stateParams', 'PublicModule', 'PublicFunction', '$location', 'Authentication', 'PublicEnum', 'usbPort',

    function($scope, $stateParams, PublicModule, PublicFunction, $location, Authentication, PublicEnum, usbPort) {
        $scope.serachText; //关键字
        $scope.day = true;
        $scope.week = false;
        $scope.month = false;
        $scope.alltime = false;

        usbPort.start();
        $scope.$on('usbPort.input', function(e, inputStr) {
            $scope.btnQuery();
        });
        $scope.$on('$destroy', function() {
            usbPort.stop();
        });

        //复选框事件
        $scope.chbChangeDay = function() { //当天查询
            if ($scope.day) {
                $scope.week = false;
                $scope.month = false;
                $scope.alltime = false;
                $scope.$digest();
                if ($scope.serachText == undefined || $scope.serachText.trim() == "") {
                    return;
                };
                var dayStartDate = calCurrentDayTime();
                var startTime = dayStartDate + ' 00:00:00';
                var endTime = dayStartDate + '23:59:59';
                //query(PublicFunction.stringToDateTime(startTime), PublicFunction.stringToDateTime(endTime));
                queryByBarcode(PublicFunction.stringToDateTime(startTime), PublicFunction.stringToDateTime(endTime));
            } else {
                $scope.day = true;
                $scope.$digest();
            }
        };
        $scope.chbChangeWeek = function() { //周查询
            if ($scope.week) {
                $scope.day = false;
                $scope.month = false;
                $scope.alltime = false;
                $scope.$digest();

                if ($scope.serachText == undefined || $scope.serachText.trim() == "") {
                    return;
                };
                //本周起止时间
                var weekStartDate = getMonDayAndSunDay()[0] + ' 00:00:00';
                var weekEndDate = getMonDayAndSunDay()[1] + ' 23:59:59';
                //var weekStartDate = calCurrentWeekTime(true) + ' 00:00:00';
                //var weekEndDate = calCurrentWeekTime(false) + ' 23:59:59';
                //query(PublicFunction.stringToDateTime(weekStartDate), PublicFunction.stringToDateTime(weekEndDate));
                queryByBarcode(PublicFunction.stringToDateTime(weekStartDate), PublicFunction.stringToDateTime(weekEndDate));
            } else {
                $scope.week = true;
                $scope.$digest();
            }
        };
        $scope.chbChangeMonth = function() { //月查询
            if ($scope.month) {
                $scope.day = false;
                $scope.week = false;
                $scope.alltime = false;
                $scope.$digest();

                if ($scope.serachText == undefined || $scope.serachText.trim() == "") {
                    return;
                };
                //本月起止时间
                var monthStartDate = calCurrentMonthTime(true) + ' 00:00:00';
                var monthEndDate = calCurrentMonthTime(false) + ' 23:59:59';
                //query(PublicFunction.stringToDateTime(monthStartDate), PublicFunction.stringToDateTime(monthEndDate));
                queryByBarcode(PublicFunction.stringToDateTime(monthStartDate), PublicFunction.stringToDateTime(monthEndDate));
            } else {
                $scope.month = true;
                $scope.$digest();
            }
        };
        $scope.chbChangeAll = function() { //全部查询
            if ($scope.alltime) {
                $scope.day = false;
                $scope.week = false;
                $scope.month = false;
                $scope.$digest();

                if ($scope.serachText == undefined || $scope.serachText.trim() == "") {
                    return;
                };
                //query();
                queryByBarcode();
            } else {
                $scope.alltime = true;
                $scope.$digest();
            }
        };

        //查询
        $scope.btnQuery = function() {
            if ($scope.serachText == undefined || $scope.serachText.trim() == "") {
                return;
            };
            if ($scope.day) {
                var dayDate = calCurrentDayTime();
                var dayStartDate = dayDate + ' 00:00:00';
                var dayEndDate = dayDate + ' 23:59:59';
                //query(PublicFunction.stringToDateTime(dayStartDate), PublicFunction.stringToDateTime(dayEndDate));
                queryByBarcode(PublicFunction.stringToDateTime(dayStartDate), PublicFunction.stringToDateTime(dayEndDate));
            } else if ($scope.week) {
                var weekStartDate = calCurrentWeekTime(true) + ' 00:00:00';
                var weekEndDate = calCurrentWeekTime(false) + ' 23:59:59';
                //query(PublicFunction.stringToDateTime(weekStartDate), PublicFunction.stringToDateTime(weekEndDate));
                queryByBarcode(PublicFunction.stringToDateTime(weekStartDate), PublicFunction.stringToDateTime(weekEndDate));
            } else if ($scope.month) {
                var monthStartDate = calCurrentMonthTime(true) + ' 00:00:00';
                var monthEndDate = calCurrentMonthTime(false) + ' 23:59:59';
                //query(PublicFunction.stringToDateTime(monthStartDate), PublicFunction.stringToDateTime(monthEndDate));
                queryByBarcode(PublicFunction.stringToDateTime(monthStartDate), PublicFunction.stringToDateTime(monthEndDate));
            } else if ($scope.alltime) {
                //query();
                queryByBarcode();
            } else if (!$scope.week && !$scope.month && !$scope.alltime) {
                PublicFunction.alert("请选择日期范围！", "查询有误");
            };

        };

        //初始化
        PublicModule.initModule($scope, 'Department');
        PublicModule.initModule($scope, 'User');
        PublicModule.initModule($scope, 'StationUser');
        PublicModule.initModule($scope, '_StationUser');

        $scope.Module.StationUser.LoadMode = PublicEnum.LoadMode.CacheAndNoPaging;
        $scope.Module.StationUser.PageSize = 15;

        $scope.Module._StationUser.LoadMode = PublicEnum.LoadMode.CacheAndNoPaging;
        $scope.Module._StationUser.PageSize = 15;

        $scope.Module.StationUser.Populate = [{
            path: 'WorkLocation',
            select: 'Code Name'
        }, {
            path: 'User',
            select: 'Code Name Department',
            populate: {
                path: 'Department',
                select: 'Code Name',
                model: 'Department'
            }
        }];

        $scope.Module.User.Populate = {
            path: 'Department',
            select: 'Code Name'
        };

        //通过刷卡取数据
        function queryByBarcode(starttime, endtime) {
            var searchText = {};
            searchText['UniqueID'] = $scope.serachText;
            //1.找部门
            $scope.Module.User.find(searchText, null, null, function(userRcds) {
                if (userRcds.length > 0) {
                    //2.根据该员工部门号找同部门员工
                    $scope.Module.User.find({
                        'Department': userRcds[0].Department
                    }, null, null, function(colUserRcds) {
                        var stationCon = {};
                        var userArr = [];
                        for (var i = 0; i < colUserRcds.length; i++) {
                            userArr.push(colUserRcds[i]._id);
                        };
                        if (starttime == undefined) { //无时间
                            stationCon = {
                                User: {
                                    $in: userArr
                                }
                            };
                        } else { //有时间
                            stationCon = {
                                $and: [{
                                    User: {
                                        $in: userArr
                                    }
                                }, {
                                    StartDateTime: {
                                        $gte: starttime
                                    }
                                }, {
                                    StartDateTime: {
                                        $lte: endtime
                                    }
                                }]
                            };
                        };
                        $scope.Module.StationUser.find(stationCon, {
                            'StartDateTime': 1
                        }, $scope.Module.StationUser.Populate, function(stationRcds) {
                            if (stationRcds.length > 0) {
                                //每人每天只取最早一条
                                var lastRcds = getFirstRcd(stationRcds);
                                $scope.Module._StationUser.Records = lastRcds;
                                //$scope.Module.StationUser.Records = stationRcds;
                            } else {
                                $scope.Module._StationUser.Records = [];
                                PublicFunction.alert("没有找到该用户所在部门的上岗记录!", "查询失败");
                            }
                            //$scope.Module.StationUser.Condition = stationCon;
                            $scope.Module._StationUser.emitOnLoadEvent();
                        });
                    });
                } else {
                    //根据Barcode没找到用户
                    PublicFunction.alert("没有找到该用户！", "查询失败");
                    return;
                };
            });
        };

        //每人每天只取最早一条
        function getFirstRcd(rcds) {
            var rtnRcds = [];
            for (var i = 0; i < rcds.length; i++) {
                if (rtnRcds.length < 1) {
                    rtnRcds.push(rcds[i]);
                } else {
                    for (var j = 0; j < rtnRcds.length; j++) {
                        if (rcds[i].User.Code == rtnRcds[j].User.Code && compareDate(rcds[i].StartDateTime, rtnRcds[j].StartDateTime)) {
                            break;
                        } else {
                            if (j == rtnRcds.length - 1) {
                                rtnRcds.push(rcds[i]);
                            };
                        };
                    };
                };
            };
            return rtnRcds;
        };

        //比较两个日期是否为同一天
        function compareDate(date1, date2) {
            var str1 = new Date(date1).toDateString();
            var str2 = new Date(date2).toDateString();
            if (str1 == str2) {
                return true;
            } else {
                return false;
            };
        }

        //查询方法
        function query(starttime, endtime) {

            var searchText = {};
            searchText['Name'] = '/' + $scope.serachText + '/';

            //1.找部门
            $scope.Module.Department.find(searchText, null, null, function(dptsRcds) {
                var userCondition = {};
                if (dptsRcds.length > 0) {
                    //2.找到部门，用部门id+关键字找用户
                    var dptArr = [];
                    for (var i = 0; i < dptsRcds.length; i++) {
                        dptArr.push(dptsRcds[i]._id);
                    };
                    userCondition = {
                        $or: [{
                            Department: {
                                $in: dptArr
                            }
                        }, {
                            Name: '/' + $scope.serachText + '/'
                        }]
                    };
                } else {
                    //2.没找到部门，用关键字找用户
                    userCondition['Name'] = '/' + $scope.serachText + '/';
                }
                $scope.Module.User.find(userCondition, null, null, function(userRcds) {
                    if (userRcds.length > 0) {
                        //3.根据用户id找上下岗关系
                        var stationCon = {};
                        var userArr = [];
                        for (var i = 0; i < userRcds.length; i++) {
                            userArr.push(userRcds[i]._id);
                        };

                        if (starttime == undefined) { //无时间
                            stationCon = {
                                User: {
                                    $in: userArr
                                }
                            };
                        } else { //有时间
                            stationCon = {
                                $and: [{
                                    User: {
                                        $in: userArr
                                    }
                                }, {
                                    StartDateTime: {
                                        $gte: starttime
                                    }
                                }, {
                                    StartDateTime: {
                                        $lte: endtime
                                    }
                                }]
                            };
                        };

                        $scope.Module.StationUser.find(stationCon, null, $scope.Module.StationUser.Populate, function(stationRcds) {
                            if (stationRcds.length > 0) {
                                $scope.Module.StationUser.Records = stationRcds;
                            } else {
                                $scope.Module.StationUser.Records = [];
                            }
                            $scope.Module.StationUser.Condition = stationCon;
                            $scope.Module.StationUser.emitOnLoadEvent();
                        });
                    } else {
                        $scope.Module.StationUser.Records = [];
                        $scope.Module.StationUser.emitOnLoadEvent();
                    }
                });
            });
        }

        //计算当天起止时间
        function calCurrentDayTime() {
            var myDate = new Date();
            var rtnTime = myDate.toLocaleDateString();
            return rtnTime;
        };

        function getMonDayAndSunDay() {
            //datevalue = new Date();
            var now = new Date(); //当前日期 
            var nowYear = now.getYear();
            nowYear += (nowYear < 2000) ? 1900 : 0; //
            var nowMonth = now.getMonth() + 1;
            var dateValue = nowYear + "-" + nowMonth + "-" + now.getDate();
            var arr = dateValue.split("-");
            //月份-1 因为月份从0开始 构造一个Date对象  
            var date = new Date(arr[0], arr[1] - 1, arr[2]);

            var dateOfWeek = date.getDay(); //返回当前日期的在当前周的某一天（0～6--周日到周一）  

            var dateOfWeekInt = parseInt(dateOfWeek, 10); //转换为整型  

            if (dateOfWeekInt == 0) { //如果是周日  
                dateOfWeekInt = 7;
            }
            var aa = 7 - dateOfWeekInt; //当前于周末相差的天数  

            var temp2 = parseInt(arr[2], 10); //按10进制转换，以免遇到08和09的时候转换成0  
            var sunDay = temp2 + aa; //当前日期的周日的日期  
            var monDay = sunDay - 6 //当前日期的周一的日期  

            var startDate = new Date(arr[0], arr[1] - 1, monDay);
            var endDate = new Date(arr[0], arr[1] - 1, sunDay);

            var sm = parseInt(startDate.getMonth()) + 1; //月份+1 因为月份从0开始  
            var em = parseInt(endDate.getMonth()) + 1;

            //  alert("星期一的日期："+startDate.getYear()+"-"+sm+"-"+startDate.getDate());  
            //  alert("星期日的日期："+endDate.getYear()+"-"+em+"-"+endDate.getDate());  
            var start = nowYear + "\\" + sm + "\\" + startDate.getDate();
            var end = nowYear + "\\" + em + "\\" + endDate.getDate();
            var result = new Array();
            result.push(start);
            result.push(end);

            return result;
        }

        //计算本周起止时间
        function calCurrentWeekTime(isStartTime) {
            var now = new Date(); //当前日期 
            var nowDayOfWeek = now.getDay(); //今天本周的第几天 
            var nowDay = now.getDate(); //当前日 
            var nowMonth = now.getMonth(); //当前月 
            var nowYear = now.getYear(); //当前年 
            nowYear += (nowYear < 2000) ? 1900 : 0; //
            var rtnTime;
            if (isStartTime) { //返回起始时间
                var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
                rtnTime = formatDate(weekStartDate);
            } else { //返回终止时间
                var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek + 1));
                rtnTime = formatDate(weekEndDate);
            };
            return rtnTime;
        }

        //计算本月起止时间
        function calCurrentMonthTime(isStartTime) {
            var now = new Date(); //当前日期 
            var nowMonth = now.getMonth(); //当前月 
            var nowYear = now.getYear(); //当前年 
            nowYear += (nowYear < 2000) ? 1900 : 0; //
            var rtnTime;
            if (isStartTime) { //返回起始时间
                var weekStartDate = new Date(nowYear, nowMonth, 1);
                rtnTime = formatDate(weekStartDate);
            } else { //返回终止时间
                //获取本月天数
                var monthStartDate = new Date(nowYear, nowMonth, 1);
                var monthEndDate = new Date(nowYear, nowMonth + 1, 1);
                var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);

                var weekEndDate = new Date(nowYear, nowMonth, days);
                rtnTime = formatDate(weekEndDate);
            };
            return rtnTime;
        }

        //格式化时间
        function formatDate(date) {
            var myyear = date.getFullYear();
            var mymonth = date.getMonth() + 1;
            var myweekday = date.getDate();
            return (myyear + "\\" + mymonth + "\\" + myweekday);
        }
    }
]);